// var mongodb = require('./db')
var mongodb = require('mongodb').MongoClient
var url = require('../settings').url
var dbName = require('../settings').dbName


function User(user) {
    this.name = user.name
    this.password = user.password
}
module.exports = User;

User.prototype.save = function save(callback) {
    var user = {
        name: this.name,
        password: this.password,
    }

    mongodb.connect(url, function (err, client) {
        if (err) {
            return callback(err)
        }

        const db = client.db(dbName)
        db.collection('users', function (err, collection) {
            if (err) {
                client.close()
                return callback(err)
            }

            collection.ensureIndex('name', { unique: true })
            collection.insert(user, { safe: true }, function (err, user) {
                client.close()
                callback(err, user)
            })
        })
    })
}

User.get = function get(username, callback) {
    mongodb.connect(url, function (err, client) {
        if (err) {
            return callback(err)
        }

        const db = client.db(dbName)
        db.collection('users', function (err, collection) {
            if (err) {
                client.close()
                return callback(err)
            }

            collection.findOne({ name: username }, function (err, doc) {
                client.close()

                if (doc) {
                    var user = new User(doc)
                    callback(err, user)
                } else {
                    callback(err, null)
                }
            })
        })
    })
}